package com.crm.model.dto;


import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.Enum.DictionaryEnum;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.common.Dictionary;
import com.crm.model.entity.contactManager.Contact;
import com.crm.model.entity.contactManager.ContactInformation;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerRawData;
import com.crm.model.entity.sys.ImportFailureLog;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.UserInfo;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.vo.customerManager.UserCustomerImportVO;
import com.crm.service.common.DictionaryDbService;
import com.crm.service.contactManager.ContactDbService;
import com.crm.service.contactManager.ContactInformationDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerRawDataDbService;
import com.crm.service.sys.ImportFailureLogDbService;
import com.crm.service.sys.UserAccountDbService;
import com.crm.service.sys.UserInfoDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @ Author ：pym
 * @ Date   ：2021/5/17 11:22
 */
@Slf4j
public class InsertUserCustomerCallable implements Callable<JSONObject> {

    private CustomerDbService customerDbService;
    private DictionaryDbService dictionaryDbService;
    private ImportFailureLogDbService importFailureLogDbService;
    private UserAccountDbService userAccountDbService;
    private UserInfoDbService userInfoDbService;
    private ContactDbService contactDbService;
    private ContactInformationDbService contactInformationDbService;
    private SysCompanyDbService sysCompanyDbService;
    private CustomerRawDataDbService customerRawDataDbService;
    private String customerPoolId;
    private List<UserCustomerImportVO> list;
    private CountDownLatch begin;
    private CountDownLatch end;
    private Integer index;

    public InsertUserCustomerCallable(CustomerDbService customerDbService, DictionaryDbService dictionaryDbService,
                                      ImportFailureLogDbService importFailureLogDbService,
                                      UserAccountDbService userAccountDbService, UserInfoDbService userInfoDbService,
                                      ContactDbService contactDbService, ContactInformationDbService contactInformationDbService,
                                      SysCompanyDbService sysCompanyDbService, CustomerRawDataDbService customerRawDataDbService,
                                      String customerPoolId, List<UserCustomerImportVO> list, CountDownLatch begin,
                                      CountDownLatch end, Integer index) {
        this.customerDbService = customerDbService;
        this.dictionaryDbService = dictionaryDbService;
        this.importFailureLogDbService = importFailureLogDbService;
        this.userAccountDbService = userAccountDbService;
        this.userInfoDbService = userInfoDbService;
        this.contactDbService = contactDbService;
        this.contactInformationDbService = contactInformationDbService;
        this.sysCompanyDbService = sysCompanyDbService;
        this.customerRawDataDbService = customerRawDataDbService;
        this.customerPoolId = customerPoolId;
        this.list = list;
        this.begin = begin;
        this.end = end;
        this.index = index;
    }

    @Override
    public JSONObject call() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //导入数量
        int importNum = 0;
        //重复的行数
        List<Integer> repeatIdStr = new ArrayList();
        //失败行数
        List<Integer> importFailIdStr = new ArrayList();
        //客户名称或统一社会信用代码为空
        List<Integer> customerNameOrCreditCodeNull = new ArrayList();
        //账号表中未找到所有人
        List<Integer> ownerNull = new ArrayList();
        //客户名称错误
        List<Integer> wrongCustomerName = new ArrayList();
        //统一社会信用代码错误
        List<Integer> wrongUnifiedSocialCreditCode = new ArrayList();
        //客户类型和统一社会信用代码为空
        List<Integer> customerTypeAndCreditCodeNull = new ArrayList();
        //个人客户联系方式为空
        List<Integer> contactInformationEmpty = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            UserCustomerImportVO userCustomerImportVO = list.get(i);
            String operateType = "2";//导入什么业务：1-线索；2-客户
            int j = (i + 2) + index * 100;
            UserInfo userInfo = null;
            try {
                //客户名称
                String customerName = CommonUtils.removeCharacters(userCustomerImportVO.getCustomerName()).replaceAll("\\(","（").replaceAll("\\)","）");
                userCustomerImportVO.setCustomerName(customerName);
                //统一社会信用代码
                String unifiedSocialCreditCode = userCustomerImportVO.getUnifiedSocialCreditCode();
                unifiedSocialCreditCode = StringUtils.isNotBlank(unifiedSocialCreditCode) ? unifiedSocialCreditCode.trim() : "";
                /*if (StringUtils.isBlank(customerName) || StringUtils.isBlank(unifiedSocialCreditCode)) {
                    importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, "客户名称或统一社会信用代码为空，客户名称："+ customerName +"，统一社会信用代码：" + unifiedSocialCreditCode,null,null,"2"));
                    customerNameOrCreditCodeNull.add(i+2);
                    continue;
                }*/
                String owner = userCustomerImportVO.getOwner();//所有人
                Customer customer = null;
                String mobilePhone = userCustomerImportVO.getMobilePhone();//手机
                String primaryContactPhone = userCustomerImportVO.getPrimaryContactPhone();//主联系人电话
                String enterpriseExternalPhone = userCustomerImportVO.getEnterpriseExternalPhone();//企业对外手机
                String enterpriseExternalLandline = userCustomerImportVO.getEnterpriseExternalLandline();//企业对外座机
                String customerTypeStr = userCustomerImportVO.getCustomerType();//客户类型
                String member = userCustomerImportVO.getMember();//会员
                String message = "，会员客户已导入";
                String modifyUnifiedSocialCreditCode = "";
                if ("个人".equals(customerTypeStr)) {
                    if (StringUtils.isBlank(mobilePhone) && StringUtils.isBlank(primaryContactPhone)
                            && StringUtils.isBlank(enterpriseExternalPhone) && StringUtils.isBlank(enterpriseExternalLandline)) {
                        //Boolean insertResult = insertErrorData(userAccount, userCustomerImportVO, userInfo, customerName, mobilePhone, primaryContactPhone, enterpriseExternalPhone, enterpriseExternalLandline, customerTypeStr, member, unifiedSocialCreditCode);
                        StringBuffer reasonForFailure = new StringBuffer().append("第"+ j +"行，个人客户联系方式为空");
                        /*if (insertResult) {
                            importNum = importNum + 1;
                            reasonForFailure.append(message);
                        } else {
                            contactInformationEmpty.add(i+2);
                        }*/
                        if (!isInsertLog(userCustomerImportVO,userInfo)) {
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, reasonForFailure.toString(),null,null,"2",userInfo));
                        }
                        contactInformationEmpty.add(i+2);
                        continue;
                    }
                }
                if (StringUtils.isNotBlank(owner)) {
                    //accountO = userAccountDbService.selectUserAccountByName(owner);
                    userInfo = userInfoDbService.getUserInfoByUserNameAndCompanyName(owner,userCustomerImportVO.getCompanyName());
                    if (userInfo == null) {
                        /*Boolean insertResult = insertErrorData(userAccount, userCustomerImportVO, userInfo, customerName, mobilePhone, primaryContactPhone, enterpriseExternalPhone, enterpriseExternalLandline, customerTypeStr, member, unifiedSocialCreditCode);
                        StringBuffer reasonForFailure = new StringBuffer().append("第"+ j +"行，账号表中未找到所有人："+ owner);
                        if (insertResult) {
                            importNum = importNum + 1;
                            reasonForFailure.append(message);
                        } else {
                            ownerNull.add(i+2);
                        }
                        if (!isInsertLog(userCustomerImportVO,null)) {
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, reasonForFailure.toString() ,null,null,"2",null));
                        }
                        continue;*/
                        //会员客户，账号表中未找到所有人，目前状态为已领取；非会员客户，账号表中未找到所有人将所有人清空，目前状态为未领取
                        StringBuffer reasonForFailure = new StringBuffer().append("第"+ j +"行，账号表中未找到所有人："+ owner);
                        if ("是".equals(member) || "过期会员".equals(member)) {
                            Boolean insertResult = insertErrorData(userAccount, userCustomerImportVO, userInfo, customerName, mobilePhone, primaryContactPhone, enterpriseExternalPhone, enterpriseExternalLandline, customerTypeStr, member, unifiedSocialCreditCode);
                            if (insertResult) {
                                importNum = importNum + 1;
                                reasonForFailure.append(message);
                            } else {
                                ownerNull.add(i+2);
                            }
                            if (!isInsertLog(userCustomerImportVO,null)) {
                                importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, reasonForFailure.toString() ,null,null,"2",null));
                            }
                            continue;
                        } else {
                            userCustomerImportVO.setOwner("");
                            reasonForFailure.append("，已清空所有人并导入");
                            if (!isInsertLog(userCustomerImportVO,null)) {
                                importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, reasonForFailure.toString() ,null,null,"2",null));
                            }
                        }
                    }
                }
                if (StringUtils.isBlank(customerName)) {
                    Boolean insertResult = insertErrorData(userAccount, userCustomerImportVO, userInfo, customerName, mobilePhone, primaryContactPhone, enterpriseExternalPhone, enterpriseExternalLandline, customerTypeStr, member, unifiedSocialCreditCode);
                    StringBuffer reasonForFailure = new StringBuffer().append("第"+ j +"行，客户名称为空");
                    if (insertResult) {
                        importNum = importNum + 1;
                        reasonForFailure.append(message);
                    } else {
                        customerNameOrCreditCodeNull.add(i+2);
                    }
                    if (!isInsertLog(userCustomerImportVO,userInfo)) {
                        importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, reasonForFailure.toString(),null,null,"2",userInfo));
                    }
                    continue;
                }
                String customerType = userCustomerImportVO.getCustomerType();//客户类型
                if (StringUtils.isBlank(customerType) && StringUtils.isBlank(unifiedSocialCreditCode)) {
                    Boolean insertResult = insertErrorData(userAccount, userCustomerImportVO, userInfo, customerName, mobilePhone, primaryContactPhone, enterpriseExternalPhone, enterpriseExternalLandline, customerTypeStr, member, unifiedSocialCreditCode);
                    StringBuffer reasonForFailure = new StringBuffer().append("第"+ j +"行，客户类型和统一社会信用代码为空");
                    if (insertResult) {
                        importNum = importNum + 1;
                        reasonForFailure.append(message);
                    } else {
                        customerTypeAndCreditCodeNull.add(i+2);
                    }
                    if (!isInsertLog(userCustomerImportVO,userInfo)) {
                        importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, reasonForFailure.toString(),null,null,"2",userInfo));
                    }
                    continue;
                }
                if (StringUtils.isBlank(customerType) && StringUtils.isNotBlank(unifiedSocialCreditCode)) {
                    userCustomerImportVO.setCustomerType("企业");
                }
                if ("企业".equals(customerTypeStr)) {
                    //去Redis判断客户名称是否存在
                    Boolean customerExist = customerDbService.isCustomerExist(customerName);
                    if (!customerExist) {
                        Boolean insertResult = insertErrorData(userAccount, userCustomerImportVO, userInfo, customerName, mobilePhone, primaryContactPhone, enterpriseExternalPhone, enterpriseExternalLandline, customerTypeStr, member, unifiedSocialCreditCode);
                        StringBuffer reasonForFailure = new StringBuffer().append("第"+ j +"行，" +customerName + "，客户名称错误");
                        if (insertResult) {
                            importNum = importNum + 1;
                            reasonForFailure.append(message);
                        } else {
                            wrongCustomerName.add(i+2);
                        }
                        if (!isInsertLog(userCustomerImportVO,userInfo)) {
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, reasonForFailure.toString(),null,null,"2",userInfo));
                        }
                        continue;
                    }
                    //根据客户名称去Redis查统一社会信用代码
                    String unifiedSocialCreditCodeRedis = customerDbService.selectUnifiedSocialCreditCode(customerName);
                    unifiedSocialCreditCode = unifiedSocialCreditCode!= null ? unifiedSocialCreditCode : "";
                    if (!unifiedSocialCreditCode.equals(unifiedSocialCreditCodeRedis)) {
                        /*Boolean insertResult = insertErrorData(userAccount, userCustomerImportVO, userInfo, customerName, mobilePhone, primaryContactPhone, enterpriseExternalPhone, enterpriseExternalLandline, customerTypeStr, member, unifiedSocialCreditCode);
                        StringBuffer reasonForFailure = new StringBuffer().append("第"+ j +"行，" +unifiedSocialCreditCode + "，统一社会信用代码错误，企查查："+ unifiedSocialCreditCodeRedis);
                        if (insertResult) {
                            importNum = importNum + 1;
                            reasonForFailure.append(message);
                        } else {
                            wrongUnifiedSocialCreditCode.add(i+2);
                        }
                        if (!isInsertLog(userCustomerImportVO,userInfo)) {
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, reasonForFailure.toString(),null,null,"5",userInfo));
                        }
                        continue;*/
                        Boolean isModify = false;
                        //根据信用代码去原始数据表中查所有人，若查出对应多个所有人不处理；若只有一个所有人，和当前客户所有人比对，一致的话修改信用代码
                        List<CustomerRawData> customerRawDataList = customerRawDataDbService.selectCustomerOwnerByUnifiedSocialCreditCode(unifiedSocialCreditCode);
                        if (customerRawDataList != null && customerRawDataList.size() > 0) {
                            if (customerRawDataList.size() == 1 && StringUtils.isNotBlank(owner)
                                    && StringUtils.isNotBlank(unifiedSocialCreditCodeRedis.replace("-",""))) {
                                if (owner.equals(customerRawDataList.get(0).getOwner())) {
                                    userCustomerImportVO.setUnifiedSocialCreditCode(unifiedSocialCreditCodeRedis);
                                    isModify = true;
                                    modifyUnifiedSocialCreditCode = "第"+ j +"行，已将统一社会信用代码：" + unifiedSocialCreditCode +"改为：" + unifiedSocialCreditCodeRedis;
                                    unifiedSocialCreditCode = unifiedSocialCreditCodeRedis;
                                }
                            }
                        }
                        if (!isModify) {
                            Boolean insertResult = insertErrorData(userAccount, userCustomerImportVO, userInfo, customerName, mobilePhone, primaryContactPhone, enterpriseExternalPhone, enterpriseExternalLandline, customerTypeStr, member, unifiedSocialCreditCode);
                            StringBuffer reasonForFailure = new StringBuffer().append("第"+ j +"行，" +unifiedSocialCreditCode + "，统一社会信用代码错误，企查查："+ unifiedSocialCreditCodeRedis);
                            if (insertResult) {
                                importNum = importNum + 1;
                                reasonForFailure.append(message);
                            } else {
                                wrongUnifiedSocialCreditCode.add(i+2);
                            }
                            if (!isInsertLog(userCustomerImportVO,userInfo)) {
                                importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, reasonForFailure.toString(),null,null,"5",userInfo));
                            }
                            continue;
                        }
                    }
                }
                /*Customer isCustomerRepeat = customerDbService.isCustomerRepeat(CommonUtils.removeCharacters(customerName), unifiedSocialCreditCode);
                if (isCustomerRepeat == null) {
                    Customer customer = getCustomer(userCustomerImportVO, userAccount, customerPoolId, userInfo);
                    Boolean insertResult = customerDbService.insertCustomer(customer);
                    if (insertResult) {
                        //导入成功
                        importNum = importNum + 1;
                    } else {
                        //导入失败
                        importFailIdStr.add(i+2);
                        importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, "插入数据失败",null,null,"2"));
                    }
                } else {
                    //客户重复
                    repeatIdStr.add(i+2);
                    importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, "客户名称或统一社会信用代码已存在，客户名称："+ customerName +"统一社会信用代码：" + unifiedSocialCreditCode,isCustomerRepeat.getCustomerId(),null,"1"));
                }*/
                if ("企业".equals(customerTypeStr)) {
                    customer = customerDbService.selectCustomerByNameAndCode(customerName, unifiedSocialCreditCode);
                } else if ("个人".equals(customerTypeStr)) {
                    String phone = getPhone(mobilePhone,primaryContactPhone,enterpriseExternalPhone,enterpriseExternalLandline);
                    customer = customerDbService.selectCustomerByNameAndPhone(customerName,phone);
                }
                if (customer == null) {
                    Boolean insertResult = insert(userAccount, userCustomerImportVO, userInfo, customerName, mobilePhone, primaryContactPhone, enterpriseExternalPhone, enterpriseExternalLandline, customerTypeStr, 0);
                    if (insertResult) {
                        //导入成功
                        importNum = importNum + 1;

                        if (!isInsertLog(userCustomerImportVO,userInfo) && StringUtils.isNotBlank(modifyUnifiedSocialCreditCode)) {
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, modifyUnifiedSocialCreditCode,null,null,"2",userInfo));
                        }
                    } else {
                        //导入失败
                        importFailIdStr.add(i+2);
                        if (!isInsertLog(userCustomerImportVO,userInfo)) {
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, "第"+ j +"行，插入数据失败",null,null,"2",userInfo));
                        }
                    }
                } else {
                    if (userInfo != null && userInfo.getAccountId().equals(customer.getOwnerId())) {
                        //客户名称、统一社会信用代码、所有人都相同不插入日志
                        //repeatIdStr.add(i+2);
                    } else {
                        //客户重复
                        repeatIdStr.add(i+2);
                        if (!isInsertLog(userCustomerImportVO,userInfo)) {
                            importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, "第"+ j +"行，客户已存在，客户名称："+ customerName +"，统一社会信用代码：" + unifiedSocialCreditCode +"，所有人：" + owner,customer.getCustomerId(),null,"1",userInfo));
                        }
                    }
                }
            } catch (Exception e) {
                //导入失败
                importFailIdStr.add(i+2);
                if (!isInsertLog(userCustomerImportVO,userInfo)) {
                    importFailureLogDbService.insertImportFailureLog(getImportFailureLog(userAccount, userCustomerImportVO, operateType, "第"+ j +"行，导入异常",null,getExceptionPrintStackTrace(e),"2",userInfo));
                }
                log.error("InsertCustomerCallable importCustomer error:", e);
            }
            end.countDown();
        }
        JSONObject result = new JSONObject();
        result.put("importNum",importNum);
        result.put("repeatIdStr",repeatIdStr);
        result.put("importFailIdStr",importFailIdStr);
        result.put("customerNameOrCreditCodeNull",customerNameOrCreditCodeNull);
        result.put("ownerNull",ownerNull);
        result.put("customerTypeAndCreditCodeNull",customerTypeAndCreditCodeNull);
        result.put("wrongCustomerName",wrongCustomerName);
        result.put("wrongUnifiedSocialCreditCode",wrongUnifiedSocialCreditCode);
        result.put("contactInformationEmpty",contactInformationEmpty);
        return result;
    }

    /**
     * 会员客户出现错误，导入一条错误数据
     * @Author pym
     * @Date  2021/7/8 10:39
     * @param userAccount 账号信息
     * @param userCustomerImportVO 客户信息
     * @param userInfo 所有人信息
     * @param customerName 客户名称
     * @param mobilePhone 手机
     * @param primaryContactPhone 主联系人电话
     * @param enterpriseExternalPhone 企业对外手机
     * @param enterpriseExternalLandline 企业对外座机
     * @param customerTypeStr 客户类型
     * @param member 会员
     * @return {@link {java.lang.Boolean}}
     */
    private Boolean insertErrorData(UserAccount userAccount, UserCustomerImportVO userCustomerImportVO, UserInfo userInfo,
                                    String customerName, String mobilePhone, String primaryContactPhone,
                                    String enterpriseExternalPhone, String enterpriseExternalLandline,
                                    String customerTypeStr, String member, String unifiedSocialCreditCode) throws Exception {
        Boolean insertResult = false;
        if ("是".equals(member) || "过期会员".equals(member)) {
            Customer customer = null;
            if ("企业".equals(customerTypeStr)) {
                customer = customerDbService.selectCustomerByNameAndCode(customerName, unifiedSocialCreditCode);
            } else if ("个人".equals(customerTypeStr)) {
                String phone = getPhone(mobilePhone,primaryContactPhone,enterpriseExternalPhone,enterpriseExternalLandline);
                customer = customerDbService.selectCustomerByNameAndPhone(customerName,phone);
            }
            if (customer == null) {
                insertResult = insert(userAccount, userCustomerImportVO, userInfo, customerName, mobilePhone, primaryContactPhone, enterpriseExternalPhone, enterpriseExternalLandline, customerTypeStr, 1);
            }
        }
        return insertResult;
    }

    /**
     * 新增
     * @Author pym
     * @Date  2021/7/8 10:42
     * @param userAccount 账号信息
     * @param userCustomerImportVO 客户信息
     * @param userInfo 所有人信息
     * @param customerName 客户名称
     * @param mobilePhone 手机
     * @param primaryContactPhone 主联系人电话
     * @param enterpriseExternalPhone 企业对外手机
     * @param enterpriseExternalLandline 企业对外座机
     * @param customerTypeStr 客户类型
     * @param memberErrorData 导入会员客户错误数据：0：否；1：是；
     * @return {@link {java.lang.Boolean}}
     */
    private Boolean insert(UserAccount userAccount, UserCustomerImportVO userCustomerImportVO, UserInfo userInfo,
                           String customerName, String mobilePhone, String primaryContactPhone, String enterpriseExternalPhone,
                           String enterpriseExternalLandline, String customerTypeStr, Integer memberErrorData) throws Exception {
        Customer customerP = getCustomer(userCustomerImportVO, userAccount, customerPoolId, userInfo);
        customerP.setMemberErrorData(memberErrorData);
        Boolean insertResult = customerDbService.insertCustomer(customerP);
        if ("个人".equals(customerTypeStr)) {
            String phone = getPhone(mobilePhone, primaryContactPhone, enterpriseExternalPhone, enterpriseExternalLandline);
            Contact contactRepeat = contactDbService.isContactRepeat(customerP.getCustomerId(), phone, customerName, 1);
            if (contactRepeat == null) {
                Contact contact = getContact(customerName, phone, customerP);//联系人管理新增联系人
                String companyName = userCustomerImportVO.getCompanyName();//所属分公司
                SysCompany sysCompany = sysCompanyDbService.selectSysCompanyByName(companyName);
                String companyId = sysCompany != null ? sysCompany.getCompanyId() : "";
                contact.setCompanyId(userInfo != null ? userInfo.getCompanyId() : companyId);
                contactDbService.addContact(contact);
                insertContactInformation(userAccount, userInfo, customerP, contact, mobilePhone, phone);
                insertContactInformation(userAccount, userInfo, customerP, contact, primaryContactPhone, phone);
                insertContactInformation(userAccount, userInfo, customerP, contact, enterpriseExternalPhone, phone);
                insertContactInformation(userAccount, userInfo, customerP, contact, enterpriseExternalLandline, phone);
            }
        }
        return insertResult;
    }

    /**
     * 获取联系人联系方式 - 手机->主联系人电话->企业对外手机->企业对外座机 顺序
     * @Author pym
     * @Date  2021/7/2 16:44
     * @param mobilePhone 手机
     * @param primaryContactPhone 主联系人电话
     * @param enterpriseExternalPhone 企业对外手机
     * @param enterpriseExternalLandline 企业对外座机
     * @return {@link {java.lang.String}}
     */
    private String getPhone(String mobilePhone, String primaryContactPhone, String enterpriseExternalPhone, String enterpriseExternalLandline) {
        String mobilePhoneStr = getPhoneStr(mobilePhone);
        if (isInteger(mobilePhoneStr) && mobilePhoneStr.length() < 15) {
            return mobilePhoneStr;
        }
        String primaryContactPhoneStr = getPhoneStr(primaryContactPhone);
        if (isInteger(primaryContactPhoneStr) && primaryContactPhoneStr.length() < 15) {
            return primaryContactPhoneStr;
        }
        String enterpriseExternalPhoneStr = getPhoneStr(enterpriseExternalPhone);
        if (isInteger(enterpriseExternalPhoneStr) && enterpriseExternalPhoneStr.length() < 15) {
            return enterpriseExternalPhoneStr;
        }
        String enterpriseExternalLandlineStr = getPhoneStr(enterpriseExternalLandline);
        if (isInteger(enterpriseExternalLandlineStr) && enterpriseExternalLandlineStr.length() < 15) {
            return enterpriseExternalLandlineStr;
        }
        return "";
    }

    /**
     * 处理联系方式
     * @Author pym
     * @Date  2021/7/2 16:47
     * @param phone 联系方式
     * @return {@link {java.lang.String}}
     */
    private String getPhoneStr(String phone) {
        return StringUtils.isNotBlank(phone) ? phone.replaceAll("-", "").replaceAll(" ", "") : "";
    }

    /**
     * 获取客户
     * @param userCustomerImportVO - 客户参数
     * @param userAccount - 账号
     * @param customerPoolId -客户池ID
     * @return
     */
    private Customer getCustomer(UserCustomerImportVO userCustomerImportVO, UserAccount userAccount,
                                 String customerPoolId, UserInfo userInfo) throws Exception {
        String accountId = userAccount.getAccountId();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
        format.setLenient(false);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
        sdf.setLenient(false);
        Customer customer = new Customer();
        customer.setCustomerId(CommonUtils.getGUID());//主键
        customer.setCustomerName(userCustomerImportVO.getCustomerName());//客户名称
        customer.setCustomerNumber(userCustomerImportVO.getCustomerNumber());//客户编号
        String customerType = userCustomerImportVO.getCustomerType();//客户类型  0企业客户 1个人客户
        if ("企业".equals(customerType)) {
            customer.setCustomerType("0");
        }
        if ("个人".equals(customerType)) {
            customer.setCustomerType("1");
        }
        //客户级别
        String customerLevel = userCustomerImportVO.getCustomerLevel();
        if (!StringUtils.isBlank(customerLevel)) {
            Dictionary customerLevelDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.CLIENT_LEVEL.getTypeCode(), customerLevel.substring(0, 1));
            if (customerLevelDic != null) {
                customer.setCustomerLevel(customerLevelDic.getDictCode());
            }
        }
        String unifiedSocialCreditCode = userCustomerImportVO.getUnifiedSocialCreditCode();
        customer.setUnifiedSocialCreditCode(StringUtils.isNotBlank(unifiedSocialCreditCode) ? unifiedSocialCreditCode.trim() : "");//统一社会信用代码
        customer.setOriginalCustomerId(userCustomerImportVO.getOriginalCustomerId());//原客户ID
        customer.setCustomerIndustryFirst(userCustomerImportVO.getCustomerIndustryFirst());//客户行业-一级
        customer.setCustomerIndustrySecond(userCustomerImportVO.getCustomerIndustrySecond());//客户行业-二级
        //customer.setProvinceCode();//省份编码
        customer.setProvinceName(userCustomerImportVO.getProvinceName());//省份名称
        //customer.setCityCode();//城市编码
        customer.setCityName(userCustomerImportVO.getCityName());//城市名称
        //customer.setCountyCode();//区/县编码
        customer.setCountyName(userCustomerImportVO.getCountyName());//区/县名称
        String detailedAddress = userCustomerImportVO.getDetailedAddress();
        if (StringUtils.isNotBlank(detailedAddress) && detailedAddress.length() > 255) {
            detailedAddress = detailedAddress.substring(0,254);
        }
        customer.setDetailedAddress(detailedAddress);//详细地址
        customer.setEnterpriseExternalPhone(userCustomerImportVO.getEnterpriseExternalPhone());//企业对外手机 -> 电话
        customer.setEnterpriseExternalLandline(userCustomerImportVO.getEnterpriseExternalLandline());//企业对外座机 -> 更多电话
        customer.setCompanyWebsite(userCustomerImportVO.getCompanyWebsite());//公司网址
        //customer.setCompanySize(userCustomerImportVO.getCompanySize());//公司规模
        String registrationNumber = userCustomerImportVO.getRegistrationNumber();
        if (StringUtils.isNotBlank(registrationNumber) && registrationNumber.length() > 50) {
            registrationNumber = registrationNumber.substring(0,49);
        }
        customer.setRegistrationNumber(registrationNumber);//注册号
        customer.setOrganizationCode(userCustomerImportVO.getOrganizationCode());//组织机构代码
        //公司类型
        String companyType = userCustomerImportVO.getCompanyType();
        if (!StringUtils.isBlank(companyType)) {
            Dictionary companyTypeDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.COMPANY_TYPE.getTypeCode(), companyType);
            if (companyTypeDic != null) {
                customer.setCompanyType(companyTypeDic.getDictCode());
            } else {
                customer.setCompanyType("22");
            }
        }
        customer.setLegalRepresentative(userCustomerImportVO.getLegalRepresentative());//法定代表人
        //注册资本
        String registeredCapital = userCustomerImportVO.getRegisteredCapital();
        if (!StringUtils.isBlank(registeredCapital)) {
            customer.setRegisteredCapital(CommonUtils.extractNumbers(registeredCapital));
        }
        //注册时间
        String registrationTime = userCustomerImportVO.getRegistrationTime();
        if (isValidDate(registrationTime,"yyyy-MM-dd")) {
            customer.setRegistrationTime(sdf.parse(registrationTime));
        }
        customer.setBusinessScope(userCustomerImportVO.getBusinessScope());//经营范围
        //企业状态
        String enterpriseState = userCustomerImportVO.getEnterpriseState();
        if (!StringUtils.isBlank(enterpriseState)) {
            Dictionary enterpriseStateDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.ENTERPRISE_STATE.getTypeCode(), enterpriseState);
            if (enterpriseStateDic != null) {
                customer.setEnterpriseState(enterpriseStateDic.getDictCode());
            } else {
                customer.setEnterpriseState("1");
            }
        }
        //资本类型
        String capitalType = userCustomerImportVO.getCapitalType();
        if (!StringUtils.isBlank(capitalType)) {
            Dictionary capitalTypeDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.CAPITAL_TYPE.getTypeCode(), capitalType);
            if (capitalTypeDic != null) {
                customer.setCapitalType(capitalTypeDic.getDictCode());
            } else {
                customer.setCapitalType("3");
            }
        }
        //参保人数
        String insuredNumber = userCustomerImportVO.getInsuredNumber();
        customer.setInsuredNumber(StringUtils.isNotBlank(insuredNumber) ? Integer.parseInt(insuredNumber) : null);
        String fax = userCustomerImportVO.getFax();
        if (StringUtils.isNotBlank(fax) && fax.length() > 50) {
            fax = fax.substring(0,49);
        }
        customer.setFax(fax);//传真
        customer.setEmail(userCustomerImportVO.getEmail());//邮箱
        customer.setRemark(userCustomerImportVO.getRemark());//备注
        //customer.setCustomerWallet();//客户钱包余额
        //customer.setCustomerShiftWallet();//客户转入额余额
        String createPeople = userCustomerImportVO.getCreatePeople();
        String companyName = userCustomerImportVO.getCompanyName();
        UserInfo userInfoC = null;
        if (StringUtils.isNotBlank(createPeople) && StringUtils.isNotBlank(companyName)) {
            userInfoC = userInfoDbService.getUserInfoByUserNameAndCompanyName(createPeople, companyName);
        }
        //创建人id
        if (userInfoC != null) {
            customer.setCreatePeopleId(userInfoC.getAccountId());
        } else {
            customer.setCreatePeopleId(userInfo != null ? userInfo.getAccountId() : accountId);
        }
        //创建时间
        String createTm = userCustomerImportVO.getCreateTm();
        if (isValidDate(createTm,"yyyy-MM-dd HH:mm")) {
            customer.setCreateTm(format.parse(createTm));
        } else {
            customer.setCreateTm(new Date());
        }
        customer.setUpdatePeopleId(accountId);//更新人id
        customer.setUpdateTm(new Date());//更新时间
        customer.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));//删除状态---0: 正常; 1: 已删除
        String owner = userCustomerImportVO.getOwner();//所有人
        if (StringUtils.isNotBlank(owner)) {
            String accountIdO = userInfo != null ? userInfo.getAccountId() : "";
            customer.setOwnerId(accountIdO);//所有人id
            customer.setCompanyName(userInfo != null ? userInfo.getCompanyId() : "");//所属公司
            customer.setCurrentStatus(Short.parseShort("1"));//目前状态---0: 未领取; 1: 已领取(我领取的客户);2: 已分配(分配给我的客户);3: 自建客户(用户模块我自建的客户);
            customer.setAccountId(accountIdO);//用户表id   查询全部客户
            customer.setReceivePeopleId(accountIdO);//领取人ID
        } else {
            customer.setCurrentStatus(Short.parseShort("0"));//目前状态---0: 未领取; 1: 已领取(我领取的客户);2: 已分配(分配给我的客户);3: 自建客户(用户模块我自建的客户);
        }
        //customer.setCustomerSource();//客户来源
        //行业
        String industry = userCustomerImportVO.getIndustry();
        if (!StringUtils.isBlank(industry)) {
            Dictionary industryDic = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.INDUSTRY.getTypeCode(), industry);
            if (industryDic != null) {
                customer.setIndustry(industryDic.getDictCode());
            } else {
                customer.setIndustry("21");
            }
        }
        //customer.setTag();//标签
        customer.setDealStatus(userCustomerImportVO.getDealStatus());//成交状态
        //customer.setUploadId();//图片上传id
        //customer.setCustomerRating();//客户评分
        //会员等级---0:非会员客户;1:VIP1;2:VIP2;3:VIP3;4:VIP4;5:VIP5;
        String member = userCustomerImportVO.getMember();
        if(!StringUtils.isBlank(member)){
            if("是".equals(member) || "过期会员".equals(member)){
                customer.setMembershipLevel(3);
            }
        }
        String primaryContactName = userCustomerImportVO.getPrimaryContactName();
        if (StringUtils.isNotBlank(primaryContactName) && primaryContactName.length() > 50) {
            primaryContactName = primaryContactName.substring(0,49);
        }
        customer.setContactPerson(primaryContactName);//联系人
        if ("个人".equals(customerType)) {
            String mobilePhone = userCustomerImportVO.getMobilePhone();//手机
            String primaryContactPhone = userCustomerImportVO.getPrimaryContactPhone();//主联系人电话
            String enterpriseExternalPhone = userCustomerImportVO.getEnterpriseExternalPhone();//企业对外手机
            String enterpriseExternalLandline = userCustomerImportVO.getEnterpriseExternalLandline();//企业对外座机
            String phone = getPhone(mobilePhone,primaryContactPhone,enterpriseExternalPhone,enterpriseExternalLandline);
            customer.setContactPersonPhone(phone);//联系人电话
        } else {
            customer.setContactPersonPhone(userCustomerImportVO.getPrimaryContactPhone());//联系人电话
        }
        //customer.setFinancialNumber();//财务人数
        //会员开始时间
        String membershipStartTm = userCustomerImportVO.getMembershipStartTm();
        if (isValidDate(membershipStartTm,"yyyy-MM-dd")) {
            customer.setMembershipStartTm(sdf.parse(membershipStartTm));
        }
        //会员到期时间
        String membershipEndTm = userCustomerImportVO.getMembershipEndTm();
        if (isValidDate(membershipEndTm,"yyyy-MM-dd")) {
            customer.setMembershipExpirationTm(sdf.parse(membershipEndTm));
        }
        //customer.setWorkplaceName();//单位名称
        customer.setCustomerPoolId(customerPoolId);//客户池id
        //customer.setAssignedPersonId();//被分配人ID
        //customer.setProtectStatus();//是否保护 0否 1是
        customer.setPotentialCustomers(0);//意向客户---0:无意向客户;1: 意向客户;
        //customer.setNewOrderRenewalCustomer();//新单/续费客户---0:新单客户;1: 续费客户;
        //customer.setLoseCustomer();//流失客户--1: 流失客户;
        customer.setOldCustomer(1);//是否是老客户：0:否;1:是
        return customer;
    }

    /**
     * 判断一个字符串是否为合法日期
     * @Author pym
     * @Date  2021/4/28 16:33
     * @param strDate -字符串
     * @return {@link {boolean}}
     */
    public boolean isValidDate(String strDate, String format) {
        boolean convertSuccess = true;
        SimpleDateFormat formatter  = new SimpleDateFormat(format);
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2018-02-29会被接受，并转换成2018-03-01
            formatter.setLenient(false);
            Date date = formatter.parse(strDate);
        } catch (Exception e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

    /**
     * 获取导入失败日志
     * @Author pym
     * @Date  2021/5/25 8:56
     * @param userAccount 账号
     * @param userCustomerImportVO 客户信息
     * @param operateType 导入什么业务：1-线索；2-客户
     * @param reasonForFailure 失败原因
     * @param dataId 重复数据ID:客户ID/
     * @param exceptionLog 异常日志
     * @param logType 日志类型：1-重复日志；2.异常日志
     * @param userInfo 所有人账号信息
     * @return {@link {com.crm.model.entity.sys.ImportFailureLog}}
     */
    private ImportFailureLog getImportFailureLog(UserAccount userAccount, UserCustomerImportVO userCustomerImportVO,
                                                 String operateType, String reasonForFailure, String dataId,
                                                 String exceptionLog, String logType, UserInfo userInfo) {
        ImportFailureLog importFailureLog = new ImportFailureLog();
        importFailureLog.setImportFailureLogId(CommonUtils.getGUID());
        importFailureLog.setOperatePeopleId(userAccount.getAccountId());
        importFailureLog.setOperateTime(new Date());
        importFailureLog.setOperateType(operateType);
        importFailureLog.setImportName(userCustomerImportVO != null ? userCustomerImportVO.getCustomerName() : "");
        importFailureLog.setReasonForFailure(reasonForFailure);
        importFailureLog.setImportData(userCustomerImportVO != null ? userCustomerImportVO.toString() : "");
        importFailureLog.setDataId(dataId);
        importFailureLog.setExceptionLog(exceptionLog);
        importFailureLog.setLogType(logType);
        importFailureLog.setAccountId(userInfo != null ? userInfo.getAccountId() : "");
        String companyName = userCustomerImportVO.getCompanyName();//所属分公司
        SysCompany sysCompany = sysCompanyDbService.selectSysCompanyByName(companyName);
        String sysCompanyId = sysCompany != null ? sysCompany.getCompanyId() : "";
        importFailureLog.setCompanyId(userInfo != null ? userInfo.getCompanyId() : sysCompanyId);
        return importFailureLog;
    }

    /**
     * 获取异常信息
     * @Author pym
     * @Date  2021/5/27 16:05
     * @param e 异常
     * @return {@link {java.lang.String}}
     */
    private static String getExceptionPrintStackTrace(Exception e){
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        pw.flush();
        sw.flush();
        return sw.toString();
    }

    /**
     * 插入日志判重
     * @Author pym
     * @Date  2021/7/1 16:52
     * @param userCustomerImportVO 客户信息
     * @param userInfo 所有人账号信息
     * @return {@link {java.lang.Boolean}}
     */
    private Boolean isInsertLog(UserCustomerImportVO userCustomerImportVO, UserInfo userInfo){
        return importFailureLogDbService.selectImportFailureLogByExample("2",userCustomerImportVO.getCustomerName(),userInfo != null ? userInfo.getCompanyId() : "",userInfo != null ? userInfo.getAccountId() : "",userCustomerImportVO != null ? userCustomerImportVO.toString() : "");
    }

    /**
     * 获取联系人
     * @Author pym
     * @Date  2021/7/2 11:47
     * @param customerName 客户名称
     * @param mobilePhone 手机号
     * @param customer 客户
     * @return {@link {com.crm.model.entity.contactManager.Contact}}
     */
    private Contact getContact(String customerName, String mobilePhone, Customer customer) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String accountId = userAccount.getAccountId();
        Contact contact = new Contact();
        contact.setContactId(CommonUtils.getGUID());
        contact.setContactName(customerName);
        contact.setContactInformation(mobilePhone);
        contact.setFollowUpTimes(0);
        contact.setCreatePeopleId(accountId);
        contact.setCreateTm(new Date());
        contact.setUpdatePeopleId(accountId);
        contact.setUpdateTm(new Date());
        contact.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        //contact.setContactState();
        //contact.setMemberGrade();
        //contact.setMergeState(0);
        contact.setContactNature(1);
        contact.setAbolishState(1);
        contact.setCustomerId(customer.getCustomerId());
        contact.setAccountId(accountId);
        //contact.setCompanyId(userAccount.getCompanyId());
        contact.setDataSource(1);
        return contact;
    }

    /**
     *
     * @Author pym
     * @Date  2021/7/2 13:41
     * @param userAccount 当前账号信息
     * @param userInfo 所有人账号信息
     * @param customerP 客户信息
     * @param contact 联系人信息
     * @param phone 联系方式
     * @param phoneS 电话
     * @return {@link }
     */
    private void insertContactInformation(UserAccount userAccount, UserInfo userInfo, Customer customerP,
                                          Contact contact, String phone, String phoneS) {
        String phoneStr = getPhoneStr(phone);
        if (isInteger(phoneStr) && phoneStr.length() < 15) {
            int contactInformationType = 1;
            if (phoneStr.equals(phoneS)) {
                contactInformationType = 0;
            }
            Boolean contactInformationRepeat = contactInformationDbService.isContactInformationRepeat(contact.getContactId(), phoneStr);
            if(!contactInformationRepeat){
                ContactInformation contactInformation = getContactInformation(userAccount, userInfo, customerP, contact, phoneStr, contactInformationType);
                contactInformationDbService.addContactInformation(contactInformation);
            }
        }
    }

    /**
     * 获取联系方式
     * @Author pym
     * @Date  2021/7/2 13:42
     * @param userAccount 当前账号信息
     * @param userInfo 所有人账号信息
     * @param customerP 客户信息
     * @param contact 联系人信息
     * @param contactInfo 联系方式
     * @param contactInformationType 联系方式类型
     * @return {@link {com.crm.model.entity.contactManager.ContactInformation}}
     */
    private ContactInformation getContactInformation(UserAccount userAccount, UserInfo userInfo, Customer customerP,
                                                     Contact contact, String contactInfo, int contactInformationType) {
        ContactInformation contactInformation = new ContactInformation();
        contactInformation.setContactInformationId(CommonUtils.getGUID());
        contactInformation.setContactInformation(contactInfo);
        contactInformation.setContactType("单位电话");
        contactInformation.setContactInformationType(contactInformationType);
        contactInformation.setCreatePeopleId(userAccount.getAccountId());
        contactInformation.setCreateTm(new Date());
        contactInformation.setUpdatePeopleId(userAccount.getAccountId());
        contactInformation.setUpdateTm(new Date());
        contactInformation.setAbolishState(1);
        contactInformation.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        contactInformation.setContactId(contact.getContactId());
        contactInformation.setCustomerId(customerP.getCustomerId());
        contactInformation.setDataSource(1);
        contactInformation.setCompanyId(userInfo != null ? userInfo.getCompanyId() : contact.getCompanyId());
        return contactInformation;
    }

    /**
     * 判断是否为整数
     * @param str
     * @return
     */
    private static boolean isInteger(String str) {
        return StringUtils.isNotBlank(str) ? str.matches("^[0-9]*$") : false;
    }
}
